package com.springmvc;

import com.springmvc.adapter.AnnotationHandlerAdapter;
import com.springmvc.adapter.HandlerAdapter;
import com.springmvc.adapter.ServletHandlerAdapter;
import com.springmvc.handler.HandlerMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

public class Servlet extends HttpServlet {

    /** 存放处理器映射器集合 */
    static Collection<HandlerMapping> handlerMappings;
    /** 存放处理器适配器 */
    static Collection<HandlerAdapter> handlerAdapters;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("dispatcher");
        // 获取到处理器
        Object handler = getHandler(req);
        // 通过适配器模式，来确定如何执行处理器的方法
        HandlerAdapter adapter = getHandlerAdapter(handler);
        Object result = null;
        try {
            if (adapter != null) {
                result = adapter.handle(req, resp, handler);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.getWriter().write(result + "");

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        // 初始化spring容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config.getInitParameter("contextConfig"));
        // 通过容器，获取到所有的处理器映射器
        Map<String, HandlerMapping> map = context.getBeansOfType(HandlerMapping.class);
        handlerMappings = map.values();
        // 通过容器，获取到所有处理器适配器
        Map<String, HandlerAdapter> handlerAdapterMap = context.getBeansOfType(HandlerAdapter.class);
        handlerAdapters = handlerAdapterMap.values();
        System.out.println("》》》》》》》》》》》》》》》》》容器初始化完成》》》》》》》》》》》》》》》》》》》");
    }

    /** 根据请求路径，获取处理器*/
    private Object getHandler(HttpServletRequest req) {
        if (handlerMappings != null) {
            for (HandlerMapping mapping : handlerMappings) {
                Object handler = mapping.getHandler(req.getRequestURI());
                return handler;
            }
        }
        return null;
    }

    /** 根据处理器，获取支持该处理器执行的适配器 */
    private HandlerAdapter getHandlerAdapter(Object handler){
        // 遍历所有的处理器适配器
        for (HandlerAdapter handlerAdapter : handlerAdapters) {
            // 如果当前适配器支持该处理器，返回该适配器
            if (handlerAdapter.support(handler)) {
                return handlerAdapter;
            }
        }
        return null;
    }
}
